/**
 * @author zhouheng
 * @date 2022年03月11日 21:33
 */

package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "ATGUIGU:cart:";

    @Override
    public Cart getCart()  throws ExecutionException, InterruptedException{
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
        if (userInfoTo.getUserId() != null) {
            // 已登录用户， 需要看是否存在临时购物车数据，若有需要进行购物车合并
            String userKey = userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItemsByKey(tempCartKey);
            for (CartItem tempCartItem : tempCartItems) {
                addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
            }
            // 清除临时购物车key
            clearCart(tempCartKey);
            List<CartItem> cartItems = getCartItemsByKey(CART_PREFIX + userInfoTo.getUserId());

            cart.setItems(cartItems);
            // 设置为非临时用户
            userInfoTo.setTempUser(false);
        } else {
            // 临时购物车
            List<CartItem> cartItems = getCartItemsByKey(tempCartKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public BigDecimal toTrade() throws ExecutionException, InterruptedException {
        Cart cart = getCart();
        BigDecimal totalAmount = cart.getTotalAmount();
        // 清空所购商品购物车
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        redisTemplate.delete(CART_PREFIX + (userInfoTo.getUserId() != null ? userInfoTo.getUserId().toString() : userInfoTo.getUserKey()));

        return totalAmount;
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItemsByKey(cartKey);
            // 获取所有被选中的购物项
            List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck()).map(item -> {
                try {
                    // 因为redis中的价格可能已经不匹配了，所以重新获取一下
                    R r = productFeignService.getPrice(item.getSkuId());
                    String price = (String) r.get("data");
                    item.setPrice(new BigDecimal(price));
                } catch (Exception e) {
                    log.warn("远程查询商品价格出错 [商品服务未启动]");
                }
                return item;
            }).collect(Collectors.toList());
            return collect;
        }
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        // 更新redis缓存
        CartItem cartItem = getCartItem(skuId);
        BoundHashOperations<String, String, Object> cartOps = getCartOps();
        cartItem.setCheck(check == 1? true : false);
        cartOps.put(skuId + "", cartItem);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, String, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        if (cartItem == null) {
            return;
        }
        cartItem.setCount(num);
        BoundHashOperations<String, String, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    /*
     * @author zhouheng
     * 根据key获取购物车信息
     * @date 2022/3/12 0012 20:18
     * @param null 
     * @return null
     */
    public List<CartItem> getCartItemsByKey(String cartKey) {
        List<CartItem> cartItems = new ArrayList<>();
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate
            .boundHashOps(cartKey);
        for (Object obj : cartOps.values()) {
            CartItem cartItem = JSON.parseObject(String.valueOf(obj), CartItem.class);
            cartItems.add(cartItem);
        }

        return cartItems;
    }

    private BoundHashOperations<String, String, Object> getCartOps(){
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = CART_PREFIX;

        if (userInfoTo.getUserId() != null) {
            cartKey += userInfoTo.getUserId();
        } else if (userInfoTo.getUserKey() != null) {
            cartKey += userInfoTo.getUserKey();
        }

        return redisTemplate.boundHashOps(cartKey);
    }

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations cartOps = getCartOps();
        String res = (String) cartOps.get(skuId+"");
        if (StringUtils.isEmpty(res)) {
            // 没有存 构建商品缓存
            CartItem cartItem = new CartItem();
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                R info = productFeignService.SkuInfo(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                // 2. 填充购物项
                cartItem.setCount(num);
                cartItem.setCheck(true);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuId);

            }, executor);
            CompletableFuture<Void> skuAttrFuture = CompletableFuture.runAsync(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            CompletableFuture.allOf(skuInfoFuture, skuAttrFuture).get();

            // 将cartItem 添加到redis
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

            return cartItem;
        } else {
            // 已经存在 更新数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            // 不太可能并发，无需加锁
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

            return cartItem;
        }

        // 若购物车中已存在该商品信息，那么只需要更改
        // 根据skuId获取商品信息


        // 购物车中无此商品 添加
    }

    @Override
    public CartItem getCartItem(long skuId) {
        // 从缓存中查询出购物车信息
        BoundHashOperations<String, String, Object> cartOps = getCartOps();
        String cartStr = (String) cartOps.get(skuId+"");

        return JSON.parseObject(cartStr, CartItem.class);
    }
}
